package com.tony.config;

import com.alibaba.fastjson.JSON;
import com.tony.dao.TonyUserDao;
import com.tony.po.TonyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.guava.GuavaCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class CacheConfig{
    @Autowired
    private TonyUserDao tonyUserDao;

    @Bean
    public CacheManager getCacheManager() {
        List<TonyUser> tonyUsers =tonyUserDao.all();
        List<String> cacheNames = new ArrayList();
        GuavaCacheManager cacheManager = new GuavaCacheManager();
        cacheManager.setCacheSpecification("maximumSize=500,expireAfterWrite=1m");

        tonyUsers.stream().forEach(tonyUser ->{
            String cacheName=tonyUser.getId().toString();
            if(cacheManager.getCache(cacheName)==null){
                cacheNames.add(cacheName);
                cacheManager.setCacheNames(cacheNames);
            }
            Cache cache = cacheManager.getCache(cacheName);
            System.out.println(tonyUser.getId()+"###"+ JSON.toJSONString(tonyUser));
            cache.put(tonyUser.getId(),tonyUser);
        });
        return cacheManager;
    }
}
